/**
 * @desc
 * 模板打包JS webpack内置.随后会包装成为一个命令
 *
 * 实际把Bar与-P文件打包压缩 ..
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/4/18
 **/
'use strict';
var webpack = require('webpack');
let fse = require('fs-extra');
let path = require('path');
let request = require('request');
let co = require('co');
var tplUtil = require('@qianmi/x-site-common/util/template-util');
let manager_host = require('../config/manager.json').host;

let templateCompileUtil =require('../util/template-compile-util');
console.log("开始编译-----------------------------------");

/**
 * 要打包的文件路径信息
 * @type {Array}
 */

  module.exports=({workBench,env})=>{
  
    let  {includeWidgetPath,templatePathList}= require( path.join(workBench,'./x-config.js'));
    
    co(function *() {
      let allTemplateConfig = [];
      let templateIndex = [];
      let tasks = [];
      for (let i = 0, ilen = templatePathList.length; i < ilen; i++) {
        let _templateConfig = yield templateCompileUtil.generateTplInfo({
          workBenchPath: workBench,
          templateConfigPath: templatePathList[i],
          envCode:env
        });
        // let config = yield templateCompileUtil._readTempConfig(templatePathList[i]);
        allTemplateConfig.push(_templateConfig);
      
        let {templateJs, templateCss} = yield  templateCompileUtil.generateTemplateConfigContent({
          workBenchPath:workBench,
          templateConfig: _templateConfig,
          envCode:env
        });
        tasks.push(extraTemplateInfo(_templateConfig,{
             jsFile: "./tplRepo/" + _templateConfig.templateName + ".js",
             cssFile: "./tplRepo/" + _templateConfig.templateName + ".css"
           }
        ));
        let templatePath = path.join(workBench, './dist/tplRepo/', _templateConfig.templateName);
        fse.outputFileSync(templatePath + ".js", templateJs);
        fse.outputFileSync(templatePath + ".css", templateCss);
      }
      templateIndex = yield tasks;

      //模板的完整信息索引文件
      fse.outputJSONSync(path.join(workBench, './dist/templateConfig.json'), allTemplateConfig);
      //用于发布后放到npm包的
      fse.outputJSONSync(path.join(workBench, './dist/templateIndex.json'), templateIndex);
      //用于本地调试的.
      yield dealLocalTemplateIndex(templateIndex,{workBench});

    }).then(()=> {
    }, err=> {
      console.error(err.stack);
    });
    
  };




function * dealLocalTemplateIndex(templateIndex,{workBench}) {
  
  _dealIndex(templateIndex, 'app',{workBench});
  _dealIndex(templateIndex, 'weixin',{workBench});
  _dealIndex(templateIndex, 'pc',{workBench});
  _dealIndexTpl(templateIndex,{workBench});
}


/**
 * 修改views/index.html中引用 的内容
 * @param templateIndex
 * @private
 */
function _dealIndexTpl(templateIndex,{workBench}) {
  
  let _templateIndex = templateIndex.map(tplItem=> {
    let href;
    if (tplItem.platForm === 'pc' && tplItem.pageType === 'index') {
      href = 'http://127.0.0.1:7070/views/prototype.html?id=' + tplItem.id + "#debug";
    } else if (tplItem.platForm === 'pc' && tplItem.pageType !== 'index') {
      href = 'http://127.0.0.1:7070/views/inner.html?id=' + tplItem.id + "#debug";
    } else if ((tplItem.platForm === 'weixin' || tplItem.platForm === 'app' ) && tplItem.pageType !== 'index') {
      href = 'http://127.0.0.1:7070/views/weixinContent.html?id=' + tplItem.id + "#debug";
    } else if ((tplItem.platForm === 'weixin' || tplItem.platForm === 'app' ) && tplItem.pageType === 'index') {
      href = 'http://127.0.0.1:7070/views/weixin.html?id=' + tplItem.id + "#debug";
    } else {
      throw new Error('未处理类型.. !!!');
    }
    return `<a href="${href}" target = "_blank">${tplItem.templateName}</a>`;
  });
  
  fse.outputFileSync(path.join(workBench, './views/index.html'),
     `
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>模板索引</title>
    </head>
    <body>
    ${_templateIndex.join('</br>\r')}
    </body>
    </html>`);
  
}

/**
 * 处理本地新打包的JS文件生成的路径 .  本地调试, 以本地信息为准
 * @param templateIndex
 * @param platForm
 * @private
 */
function _dealIndex(templateIndex, platForm,{workBench}) {
  
  let templateCode2Index = {};
  for (let i = 0, ilen = templateIndex.length; i < ilen; i++) {
    templateCode2Index[templateIndex[i].templateName] = i;
  }
  
  let appTemplateIndexPath = path.join(workBench, './template-index/' + platForm + '-template-index.json');
  let appTemplateIndex = fse.readJsonSync(appTemplateIndexPath);
  
  let platFormTpl2Index = {};
  for (let i = 0, ilen = appTemplateIndex.length; i < ilen; i++) {
    platFormTpl2Index[appTemplateIndex[i].templateName] = i;
  }
  
  for (let i = 0, ilen = templateIndex.length; i < ilen; i++) {
    if (templateIndex[i].platForm === platForm) {
      let jsFile = path.join('/dist/', templateIndex[i].jsFile),
         cssFile = path.join('/dist/', templateIndex[i].cssFile);
      if (templateIndex[i] && platFormTpl2Index[templateIndex[i].templateName]) {
        appTemplateIndex[platFormTpl2Index[templateIndex[i].templateName]].jsFile = jsFile;
        appTemplateIndex[platFormTpl2Index[templateIndex[i].templateName]].cssFile = cssFile;
        appTemplateIndex[platFormTpl2Index[templateIndex[i].templateName]].id = templateIndex[i].id;
      } else {
        appTemplateIndex.push(Object.assign({}, templateIndex[i], {jsFile, cssFile}))
      }
    }
  }
  
  
  fse.outputJsonSync(appTemplateIndexPath, appTemplateIndex);
  fse.outputFileSync(appTemplateIndexPath.replace('-template-index.json', '-template-index.js'),
     tplUtil.transfertpIndex2JsFile(appTemplateIndex));
}

let _detailInfo = `"detailInfo":{
      "priviewImage":"",
      "detailImage":"",
      "priviewHtml":"",
      "author":"",
      "authorHtml":"",
      "browserSupport":{

      },
      "desc":""
    },`;
/**
 * 提取模板信息
 */
function *extraTemplateInfo(templateConfigInfo, {jsFile, cssFile}) {
  let platform = templateConfigInfo.platForm;
  let styleType = templateConfigInfo.styleType;
  let templateIndex = yield getTemplateIndex(platform);
  let exist = false;
  for (let i = 0; i < templateIndex.length; i++) {
    if (templateIndex[i].templateName === templateConfigInfo.templateName) {
      exist = true;
    }
  }
  if (!exist && styleType === 'adapter') {
    throw new Error('新模板的风格styleType需为standard:::'+templateConfigInfo.templateName);
  }

  if (styleType === 'standard' && (!templateConfigInfo.color2Class || !templateConfigInfo.acceptStyles)) {
    throw new Error('standard风格里须有color2Class和acceptStyles属性:::'+templateConfigInfo.templateName);
  }
  
  let acceptStyles = (templateConfigInfo.acceptStyles && templateConfigInfo.acceptStyles.map(item=> {
       return {name: item.name, title: item.title, background: item.background}
     })) || [];
  if (!styleType) {
    styleType = 'none';
  }
  
  if (!templateConfigInfo.detailInfo) {
    throw new Error('模板不包含detailInfo信息,' + _detailInfo);
  }
  
  return {
    templateName: templateConfigInfo.templateName,
    id: templateConfigInfo.id,
    detailInfo: templateConfigInfo.detailInfo,
    isShow: templateConfigInfo.isShow,
    templateName_cn: templateConfigInfo.templateName_cn,
    isDoublePlatformTpl: templateConfigInfo.isDoublePlatformTpl || false,
    jsFile: jsFile,
    cssFile: cssFile,
    pageCode: templateConfigInfo.pageCode,
    pageType: templateConfigInfo.pageType,
    platForm: templateConfigInfo.platForm,
    updateTime: templateConfigInfo.updateTime || '',
    systemCode: templateConfigInfo.systemCode,
    styleType,
    acceptStyles,
  }
}

function getTemplateIndex(platform) {
  return new Promise((resolve,reject)=>{
    request(manager_host + "/resources/" + platform + "/templateIndex", function (err, res, body) {
      if (!err && res.statusCode === 200) {
        resolve(JSON.parse(body));
      } else {
        reject({});
      }
    })
  })
}